<template>
  <div class='publish-page'>
    <el-card>
      <div slot="header">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>发布文章</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表单 -->
      <el-form label-width="120px" :model="articleForm" :rules="articleRules">
        <el-form-item label="标题：" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" style="width:400px"></el-input>
        </el-form-item>

        <el-form-item label="频道：" prop="channel_id">
          <my-channel @channelChange="channelChangeFn" :channel_id="articleForm.channel_id"></my-channel>
        </el-form-item>

        <el-form-item label="封面："  prop="cover">
          <el-radio-group @change="changeCoverType()" v-model="articleForm.cover.type" >
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <div v-if="articleForm.cover.type===1||articleForm.cover.type===3">
            <el-upload
              ref="upload"
              action="http://geek.itheima.net/v1_0/upload"
              list-type="picture-card"
              name="image"
              :file-list="fileList"
              :on-remove="removeFile"
              :limit="articleForm.cover.type"
              :on-success="uploadSuccess"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="内容：" prop="content">
          <!-- <input v-html="articleForm.content"/> -->
          <quill-editor @blur="checkContent()" v-model="articleForm.content" :options="editorOption"/>
          <el-form ref="articleForm" :model="articleForm" :rules="articleRules" label-width="120px"></el-form>
        </el-form-item>

        <el-form-item label="">
          <el-button type="primary" @click="submit(false)">发布文章</el-button>
          <el-button @click="submit(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import MyChannel from './components/my-channel.vue'
import { getArticleAPI, publishArticleAPI, editArticleAPI } from '../../api/index.js'

export default {
  name: 'PublishPage',
  components: {
    MyChannel,
    quillEditor
  },
  data () {
    // 自定义校验规则
    const checkCoverFn = (rule, value, cb) => {
      // 自己对value进行校验
      if (value.type === 1) {
        if (!value.images[0]) {
          return cb(new Error('请选择一张封面图'))
        }
      }
      if (value.type === 3) {
        if (!(value.images[0] && value.images[1] && value.images[2])) {
          return cb(new Error('请选择三张封面图'))
        }
      }
      // 代码走到这，校验成功
      cb()
    }
    return {
      fileList: [],
      // 表单数据
      articleForm: {
        id: null,
        title: null,
        content: null,
        cover: {
          type: 1,
          images: []
        },
        channel_id: null
      },
      editorOption: {},
      // 校验规则
      articleRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 4, max: 50, message: '文章标题4-50字符', trigger: 'blur' }
        ],
        cover: [
          // 需要自定义
          { validator: checkCoverFn, trigger: 'change' }

        ],
        channel_id: [
          { required: true, message: '请选择文章频道', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取频道列表
    channelChangeFn (channelId) {
      this.articleForm.channel_id = channelId
    },
    checkContent () {
      // 校验内容表单项
      this.$refs.articleForm.validateField('content')
    },
    async init (id) {
      if (id) {
        const { data: res } = await getArticleAPI(id)
        console.log(res)
        this.articleForm = res.data
        const images = this.articleForm.cover.images
        images.forEach((element, index) => {
          const file = {
            name: index,
            url: element
          }
          this.fileList.push(file)
        })
        console.log(this.fileList)
      }
    },
    // 切换封面类型
    changeCoverType () {
      // 重置数据
      this.articleForm.cover.images = []
      // 重置组件
      this.$refs.upload && this.$refs.upload.clearFiles()
      // 自己再次校验
      this.$refs.articleForm.validateField('cover')
    },
    // 上传图片
    uploadSuccess (res, file, fileList) {
      this.articleForm.cover.images.push(res.data.url)
      console.log(this.articleForm.cover.images)
    },
    // 删除文件
    removeFile (file) {
      // 主动：删除images数组中对应的图片
      // file 中保存了之前上传图片响应的信息 response.data.url 图片地址
      // 根据这个图片地址找到images对应的索引，通过splice(索引,1) 删除图片
      const index = this.articleForm.cover.images.findIndex(item => item === file.response.data.url)
      this.articleForm.cover.images.splice(index, 1)
      // 自己再次校验
      this.$refs.articleForm.validateField('cover')
    },
    // 发布文章
    async submit (formal) {
      try {
        const id = this.articleForm.id
        let res
        let message
        if (id === null) {
          res = await publishArticleAPI(formal, this.articleForm)
          message = '发布成功'
        } else {
          res = await editArticleAPI(id, formal, this.articleForm)
          message = '修改成功'
        }
        console.log(res)
        this.$message.success(message)
        this.$router.push('/layout/article')
      } catch (error) {
        this.$message.error('发布失败')
        console.log(error)
      }
    }
  },
  mounted () {},
  watch: {
    $route: {
      immediate: true, // 一旦监听到路由的变化立即执行
      handler () {
        this.init(this.$route.params.id)
      }
    }

  }
}
</script>

<style scoped lang='less'>
::v-deep .ql-editor {
  min-height: 300px;
}
::v-deep .el-upload-list__item {
  transition: none;
}
</style>
